<?php

namespace addons\qingdong\model;

use addons\qingdong\model\Staff as StaffModel;
use app\admin\model\AuthGroup;
use think\Model;
use traits\model\SoftDelete;

/**
 * 审批流程设置
 */
class Flow extends Model
{
    use SoftDelete;
    const CONTRACT_STATUS='contract';
    const RECEIVABLES_STATUS='receivables';
    const CONSUME_STATUS='consume';
    const ACHIEVEMENT_STATUS='achievement';
    const APPROVAL_STATUS='approval';
    const CARD_STATUS='card';//补卡
    const LEAVE_STATUS='leave';//请假

    // 表名,不含前缀
    protected $name = 'qingdong_flow';
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';
    // 追加属性
    protected $append = [
        'groups_text',
        'last_admin_text',
    ];

    /**
     * 角色组
     */
    public function getGroupsTextAttr($value, $data)
    {
        $group_ids = $data['group_ids'] ?? "";
        if(empty($group_ids)){
            return '全公司';
        }
        $groups = AuthGroup::where(['id' => ['in', $group_ids]])->field('name')->select();
        $names=[];
        foreach ($groups as $v){
            $names[]=$v['name'];
        }
        return implode(',',$names);
    }

    /**
     * 最后修改人
     */
    public function getLastAdminTextAttr($value,$data){
        $admin_id=$data['last_admin_id']??'';
        return \app\admin\model\Admin::where(['id'=>$admin_id])->value('nickname');
    }

    /**
     * 获取审批信息
     * @param $type
     * @return array|mixed
     */
    protected static function getFlowByTypes($type)
    {

        $staff = Staff::info();
        $type=explode('_',$type);
        if ($type[0] == self::APPROVAL_STATUS) {
            $flow = FormApproval::where(['id' => $type[1]])->find();
            return $flow;
        }
        $group_ids = $staff->group_ids;
        $group_ids = explode(',', $group_ids);
        $flows = Flow::where(['relation_type' => $type[0]])->order('id desc')->select();
        $flows = collection($flows)->toArray();
        $flow = [];
        foreach ($flows as $v) {
            if(empty($v['group_ids'])){
                $flow = $v;
                break;
            }
            $ids = explode(',', $v['group_ids']);
            if (array_intersect($group_ids, $ids)) {
                $flow = $v;
                break;
            }
        }
        return $flow;
    }

    /**
     * 获取审批
     * @param $type
     * @return array|false
     */
    public static function getsteplist($type){
        $examineFlowData = Flow::getFlowByTypes($type);
        if (!$examineFlowData) {
            //无可用审批流，请联系管理员
            return false;
        }

        $staff = Staff::info();
        $flow_staff_ids=[];
        //自选还是流程(1固定,0自选)
        if ($examineFlowData['status'] == 1) {
            $examine_ids = json_decode($examineFlowData['examine_ids'], true);
            if (!$examine_ids) {
                //无可用审批流，请联系管理员
                return false;
            }
            $pid = StaffModel::where(['id' => $staff->id])->value('parent_id');
            $stepList = [];
            foreach ($examine_ids as $ks => $vs) {
                $stepInfo = [];
                $stepInfo['order_id'] = $ks + 1;//第几级
                if ($vs['stafftype'] == 3) {//直属上级
                    $s = StaffModel::where(['id' => $pid])->field('id,name,img')->select();
                    $s = collection($s)->toArray();
                    $stepInfo['status'] = $vs['stafftype'];
                    $stepInfo['stafflist'] = $s;
                    $stepInfo['staffids'] = $pid;
                    $stepList[] = $stepInfo;
                    $flow_staff_ids[]=$pid;
                } else if ($vs['stafftype'] == 1) {//指定员工(任意一人)
                    $s = StaffModel::where(['id' => ['in', $vs['staff_id']]])->field('id,name,img')->select();
                    $s = collection($s)->toArray();
                    $stepInfo['status'] = $vs['stafftype'];
                    $stepInfo['stafflist'] = $s;
                    $stepInfo['staffids'] = $vs['staff_id'];
                    $stepInfo['relation'] = 2;
                    $stepList[] = $stepInfo;
                    $flow_staff_ids[]=$vs['staff_id'];

                } else {//指定员工(并签)
                    $s = StaffModel::where(['id' => ['in', $vs['staff_id']]])->field('id,name,img')->select();
                    $s = collection($s)->toArray();
                    $stepInfo['status'] = $vs['stafftype'];
                    $stepInfo['staffids'] = $vs['staff_id'];
                    $stepInfo['stafflist'] = $s;
                    $stepInfo['relation'] = 1;
                    $stepList[] = $stepInfo;
                    $flow_staff_ids[]=$vs['staff_id'];
                }
            }
        } else {
            $stepList = [];
        }
        $data = [];
        $data['flow_staff_ids'] = implode(',',$flow_staff_ids); //审批id
        $data['flow_id'] = $examineFlowData['id']; //审批id
        $data['order_id']=$stepList?$stepList[0]['order_id']:0;
        $data['status'] = $examineFlowData['status']; //1固定,0自选
        $data['stepList'] = $stepList ?: [];//审批流程
        return $data;
    }

    /**
     * 获取审批详情
     * @param $type
     * @return array|false
     */
    public static function getstepdetail($relation_type,$relation_id){
        switch ($relation_type){
            case self::CONTRACT_STATUS:
                $model=new Contract();
                break;
            case self::RECEIVABLES_STATUS:
                $model=new Receivables();
                break;
            case self::CONSUME_STATUS:
                $model=new Consume();
                break;
            case self::ACHIEVEMENT_STATUS:
                $model=new AchievementRecords();
                break;
            case self::APPROVAL_STATUS:
                $model=new Approval();
                break;
            case self::CARD_STATUS:
                $model=new AttendanceCard();
                break;
            case self::LEAVE_STATUS:
                $model=new Leave();
                break;
        }
        $row=$model->get($relation_id);
        if(empty($row)){
            return false;
        }
        if($relation_type==self::APPROVAL_STATUS){
            $examineFlowData = FormApproval::withTrashed()->where(['id'=>$row->formapproval_id])->find();
        }else{
            $examineFlowData = Flow::withTrashed()->where(['id'=>$row->flow_id])->find();
        }
        if (!$examineFlowData) {
            //无可用审批流，请联系管理员
            return false;
        }
        $staff_id=$row->create_staff_id??($row->staff_id??$row->owner_staff_id);
        $records=ExamineRecord::where(['relation_type'=>$relation_type,
            'relation_id'=>$relation_id])->field('check_time,status,content,check_staff_id')->select();
        $records=collection($records)->toArray();
        $examineRecord=[];
        foreach ($records as $v){
            $examineRecord[$v['check_staff_id']]=$v;
        }
        $examine_ids = json_decode($examineFlowData['examine_ids'], true);
        //自选还是流程(1固定,0自选)
        if ($examineFlowData['status'] == 1) {
            $pid = StaffModel::where(['id' => $staff_id])->value('parent_id');
            $stepList = [];
            foreach ($examine_ids as $ks => $vs) {
                $stepInfo = [];
                $stepInfo['order_id'] = $ks + 1;//第几级
                if ($vs['stafftype'] == 3) {//直属上级
                    $s = StaffModel::where(['id' => $pid])->field('id,name,img')->select();
                    $s = collection($s)->toArray();

                    $stepInfo['status'] = $vs['stafftype'];
                    $stepInfo['stafflist'] = $s;
                    $stepInfo['staffids'] = $pid;
                } else if ($vs['stafftype'] == 1) {//指定员工(任意一人)
                    $s = StaffModel::where(['id' => ['in', $vs['staff_id']]])->field('id,name,img')->select();
                    $s = collection($s)->toArray();
                    $stepInfo['status'] = $vs['stafftype'];
                    $stepInfo['stafflist'] = $s;
                    $stepInfo['staffids'] = $vs['staff_id'];
                    $stepInfo['relation'] = 2;
                } else {//指定员工(并签)
                    $s = StaffModel::where(['id' => ['in', $vs['staff_id']]])->field('id,name,img')->select();
                    $s = collection($s)->toArray();
                    $stepInfo['status'] = $vs['stafftype'];
                    $stepInfo['staffids'] = $vs['staff_id'];
                    $stepInfo['stafflist'] = $s;
                    $stepInfo['relation'] = 1;
                }
                //审批记录
                foreach ($stepInfo['stafflist'] as &$staffinfo) {
                    if (isset($examineRecord[$staffinfo['id']])) {
                        $staffinfo['examine_reord'] = $examineRecord[$staffinfo['id']];
                    } else {
                        $staffinfo['examine_reord'] = ['status' => 0, 'check_time' => '', 'content' => ''];
                    }
                }
                $stepList[] = $stepInfo;

            }
        } else {
            $stepList = [];
            $s = StaffModel::where(['id' => ['in', $row['flow_staff_ids']]])->field('id,name,img')->select();
            $s = collection($s)->toArray();
            $stepInfo['staffids'] = $row['flow_staff_ids'];
            $stepInfo['stafflist'] = $s;
            //审批记录
            foreach ($stepInfo['stafflist'] as &$staffinfo) {
                if (isset($examineRecord[$staffinfo['id']])) {
                    $staffinfo['examine_reord'] = $examineRecord[$staffinfo['id']];
                } else {
                    $staffinfo['examine_reord'] = ['status' => 0, 'check_time' => '', 'content' => ''];
                }
            }
            $stepList[] = $stepInfo;
        }
        $is_check=0;
        $staff=Staff::info();
        if(isset($examineRecord[$staff->id])){
            if($examineRecord[$staff->id]['status'] == 0){
                $is_check=1;
            }
        }
        $data = [];
        $data['flow_id'] = $examineFlowData['id']; //审批id
        $data['flow_staff_ids'] = $row['flow_staff_ids'];
        $data['order_id'] = $row['order_id'];
        $data['status'] = $examineFlowData['status']; //1固定,0自选
        $data['stepList'] = $stepList ?: [];//审批流程
        $data['is_check'] = $is_check;//审批权限(1有)
        $data['is_recheck'] =  ($staff->id == $staff_id)?1:0;//撤销审批权限(1有)
        return $data;
    }

    /**
     * 给下一审批人发送审批通知
     */
    public static function sendStepRecord($flow,$relation_type,$relation_id,$check_staff_ids=''){
        if(!is_array($check_staff_ids)){
            $check_staff_ids=explode(',',$check_staff_ids);
        }
        if($flow['status'] == 0){//发起人自选

            $diff              = array_diff(explode(',',$flow['flow_staff_ids']), $check_staff_ids);
            if(empty($diff)){
                return ['status'=>true,'order_id'=>1];
            }else{
                $diff=array_values($diff);
                ExamineRecord::addExaminse($relation_type,$relation_id, $diff[0]);

                return ['status'=>false,'order_id'=>1];
            }
        }
       foreach ($flow['stepList'] as $v){
           $staffIds=explode(',',$v['staffids']);
           $is_check=0;//是否通过
           if($v['status'] == 1){//任意一人 或签
               foreach ($staffIds as $sid) {
                   if (in_array($sid, $check_staff_ids)) {
                       $is_check = 1;
                   }
               }

           }else{//直属上级和并签
               $is_check = 1;
               foreach ($staffIds as $sid) {
                   if (!in_array($sid, $check_staff_ids)) {
                       $is_check = 0;
                   }
               }
           }
           if ($is_check != 1) {//发送审批通知
               foreach ($staffIds as $sid) {
                   if (!in_array($sid, $check_staff_ids)) {
                       ExamineRecord::addExaminse($relation_type, $relation_id, $sid);
                   }
               }
               return ['status'=>false,'order_id'=>$v['order_id']];
           }

       }

       return ['status'=>true,'order_id'=>$v['order_id']+1];
    }
}